<?php

/**
 * This is the model class for table "subscription".
 *
 * The followings are the available columns in table 'subscription':
 * @property integer $id
 * @property string $email
 * @property string $create_time
 */
class Subscription extends EActiveRecord {
    const ACTIVE = 1;
    const INACTIVE = 0;

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'setUpdateOnCreate' => true,
            ),
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Subscription the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'subscription';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('email', 'required',),
            array('email', 'length', 'max' => 255,),
            array('email', 'email',),
            array('email', 'unique', 'message' => '{value} вече е абониран!', 'criteria' => array('scopes' => array('active'))),
            array('create_time, update_time, is_active', 'safe',),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, email, create_time', 'safe', 'on' => 'search',),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'email' => 'Email',
            'create_time' => 'Create Time',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('create_time', $this->create_time, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    public function scopes() {
        return array(
            'active' => array(
                'condition' => 'is_active=' . self::ACTIVE,
            ),
            'inactive' => array(
                'condition' => 'is_active=' . self::INACTIVE,
            ),
        );
    }

    /**
     * Filters by email.
     *
     * @param string $email Defaults to null - uses the email property value.
     * @return Subscription 
     */
    public function byMail($email=null) {
        if ($email === null)
            $email = $this->email;

        $alias = $this->getTableAlias(true, true);
        $this->getDbCriteria()->mergeWith(new CDbCriteria(array(
                    'condition' => $alias . '.email=:email',
                    'params' => array(':email' => $email),
                )));
        return $this;
    }

    protected function beforeSave() {
        if ($this->getScenario() == 'insert') {
            $model = $this->byMail()->inactive()->find();
            if ($model === null)
                return parent::beforeSave();

            // was subscribed, -> resubscribing.
            $model->is_active = 1;
            // TODO: think of a way to track wether the resubscription is
            $model->save(false, array('is_active', 'update_time'));
            $this->_resubscribed = 1;
            return false;
        }
        else
            return parent::beforeSave();
    }

    private $_resubscribed = 0;

    public function getIsResubscribed() {
        return (bool) $this->_resubscribed;
    }
}